package com.cn.genericity.binary;

import java.util.LinkedList;

/**
 * @author hels
 * @version 1.0
 * @date 2022/12/13 15:05
 */
public class Node<T extends Node> {
    public int value;
    public T left;
    public T right;

    public Node(int value) {
        this.value = value;
    }

    public   void printTree(T head) {
        System.out.println("Binary Tree:");
        printInOrder(head, 0, "H", 17);
        System.out.println();
    }

    private  <T extends Node> void printInOrder(T head, int height, String to, int len) {
        if (head == null) {
            return;
        }
        printInOrder(head.right, height + 1, "v", len);
        String val = to + head.value + to;
        int lenM = val.length();
        int lenL = (len - lenM) / 2;
        int lenR = len - lenM - lenL;
        val = getSpace(lenL) + val + getSpace(lenR);
        System.out.println(getSpace(height * len) + val);
        printInOrder(head.left, height + 1, "^", len);
    }

    private static String getSpace(int num) {
        String space = " ";
        StringBuffer buf = new StringBuffer("");
        for (int i = 0; i < num; i++) {
            buf.append(space);
        }
        return buf.toString();
    }

    public<T extends Node> T getNodeInstance(int[] arr, T head) {
        if (arr == null || arr.length < 1) return null;


        LinkedList<Integer> arrQueue = new LinkedList<>();
        for (int num : arr) {
            arrQueue.add(num);
        }

//      向下转型：必须显式指明父类对象要转换的子类对象
        head = (T) new Node(arrQueue.poll());
        LinkedList<T> queue = new LinkedList<>();
        queue.add(head);
        T current = null;
        while (!arrQueue.isEmpty()) {
            T newNode = (T)new Node(arrQueue.poll());
            current = queue.peek();

            if (current.left == null) {
                current.left = newNode;
            } else if (current.right == null) {
                current.right = newNode;
                queue.poll();
            }
            queue.add(newNode);
        }
        System.out.println(head);
        System.out.println(head instanceof  Node);
        T res = (T)head;
        return res;
    }

}
